<template>
  <!--  原生摄像头-->
  <div>
    <div class="box1">
      <video
        id="videoCamera"
        class="canvas"
        :width="videoWidth"
        :height="videoHeight"
        autoPlay
      ></video>
      <canvas
        id="canvasCamera"
        class="canvas"
        :width="canvasWidth"
        :height="canvasHeight"
      ></canvas>
    </div>
  </div>
</template>

<script>
export default {
  name: "cameraVideo",
  data() {
    return {
      os: false, //控制摄像头开关
      thisVideo: null,
      thisContext: null,
      thisCancas: null,
      imgSrc: "",
      videoWidth: 500,
      videoHeight: 400,
      canvasWidth:500,
      canvasHeight:400
    };
  },
  created() {
    this.openCamera();
  },
  mounted(){
    this.timer = setInterval(this.ongoing, 3000);
  },
  beforedestroy(){
    this.stopCamera()
  },
  methods: {
    ongoing(){
      console.log('摄像头ongoing')
      this.photographBtn();
      this.submitBtn();
    },
    submitBtn() {
      console.log('Into submitBtn');
      var dataToSend = {
          'imgData': this.imgSrc
      };
      var url = this.global.ip
      this.$http.post(url +'/api/img', dataToSend).then(res => {
          var focus = JSON.parse(JSON.stringify(res.data))
          console.log((focus.focus));
          if (focus.focus===1) {
            this.global.unfocus += 1
          }else{
            console.log('this.global.focus')
            this.global.focus += 1
          }
      });
    },
    openCamera() {
      console.log('Into openCamera')
      this.$nextTick(() => {
        const _this = this;
        this.os = false;
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)",
          },
        };
        console.log('aboutTo navigator.mediaDevices')
        navigator.mediaDevices.getUserMedia(constraints)
          .then(function (stream) {
            if ("srcObject" in _this.thisVideo) {
              console.log('in _this.thisVideo')
              _this.thisVideo.srcObject = stream;
            } else {
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function () {
              _this.thisVideo.play();
            };
          })
          .catch((err) => {
            console.log(err);
            this.$message({
              message: "没有开启摄像头权限或浏览器版本不兼容",
              type: "warning",
            });
          });
      });
    },
    photographBtn() {
      // 点击，canvas画图
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接 >>> 这里是base64格式的图片
      this.imgSrc = this.thisCancas.toDataURL("image/png");
    },
    //清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    //重置画布
    resetBtn() {
      this.imgSrc = "";
      this.clearCanvas("canvasCamera");
    },
    //关闭摄像头
    stopCamera() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true; //切换成打开摄像头
      }
    },
    downloadFile(fileName, content) {
        let aLink = document.createElement('a');
        let blob = this.base64ToBlob(content); //new Blob([content]);
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));//兼容火狐
    }, 
    base64ToBlob(code) {
        let contentType = code.split(':')[1];
        let raw = window.atob(code);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], { type: contentType });
    },
    downloadpic(){
      this.downloadFile("/hi.png",this.imgSrc)
    },
  },
};
</script>

<style scoped>
#canvasCamera{
  margin-left: 20px;
}
.box1{
  background:rgba(249,93,62,0.1)
}
.canvas {
  display: none;/* xujiawei是大神*/
}
</style>